package com.ebupt.migu.music.commons.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Intellij IDEA.
 * User:  liuyangyang@cd.ebupt.com
 * Date:  2019/10/23
 */
public class JsonUtils {

    /**
     * 对象转JSON字符串
     *
     * @param object
     * @return
     */
    public static String obj2Json(Object object) {
        return JSON.toJSONString(object);
    }

    /**
     * JSON字符串转对象
     *
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(String str, Class<T> clazz) {
        return JSON.parseObject(str, clazz);
    }

    /**
     * json字符串转含泛型对象
     *
     * @param str
     * @param type
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(String str, TypeReference<T> type) {
        return JSON.parseObject(str, type);
    }

    /**
     * JSON字符串转对象List
     *
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> json2Array(String str, Class<T> clazz) {
        return JSON.parseArray(str, clazz);
    }

    /**
     * JavaBean转换Map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> beanToMap(Object object) {
        Map<String, Object> result = new HashMap<>();
        //获得类的的属性名数组
        Field[] fields = object.getClass().getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                String name = new String(field.getName());
                result.put(name, field.get(object));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
